package com.bot.rf.util;

import com.bot.rf.entity.BookInfo;
import com.bot.rf.sql.util.LocalSqlUtil;

import java.io.*;
import java.util.*;

import static com.bot.rf.util.MyLogger.LOGGER;

/**
 * @program: report-form-demo
 * @description: 文件工具类
 * @author: zyy
 * @create: 2021-02-24 14:18
 **/
public class FileUtil {

    /**
     * 创建文件
     * @param path
     */
    public static void createFile(String path) {
        File file = new File(path);
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 创建文件夹
     * @param path
     */
    public static void createMkdir(String path){
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
    }

    /**
     * 按行读取文件
     * @param fileName 文件名
     * @return 返回List数组
     */
    public static List<String> readFileByLine(String fileName) {
        List<String> result = new ArrayList<>();
        if (!new File(fileName).exists()) {
            result.add("");
        } else {
            try {
                BufferedReader reader = new BufferedReader(new FileReader(fileName));
                String lineContent;
                while ((lineContent = reader.readLine()) != null) {
                    result.add(lineContent);
                }
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 读文件
     * @param fileName 文件名
     * @return 返回List数组
     */
    public static Set<String> readFileBackSet(String fileName) {
        List<String> list = readFileByLine(fileName);
        Set<String> set = new HashSet<>(list);
        LOGGER.info("文件去重后 " + set.size() + "条，重复 " + (list.size() - set.size()) + "条");
        return set;
    }


    /**
     * 写入文件
     *
     * @param fileName   文件名
     * @param isAddition 是否追加
     * @param contents   文件内容
     */
    public static void writeFile(String fileName, boolean isAddition, List<?> contents) {
        try {
            File file = new File(fileName);
            if (!file.exists()) {
                file.createNewFile();
            }
            BufferedWriter writer = new BufferedWriter(new FileWriter(fileName, isAddition));
            for (Object obj : contents) {
                if (obj.toString().length() == 0) {
                    continue;
                }
                writer.write(obj.toString());
                writer.newLine();
            }
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除文件
     *
     * @param fileName 文件名
     */
    public static void deleteFile(String fileName) {
        File file = new File(fileName);
        if (file.exists()) {
            // 文件夹
            if (file.isDirectory()) {
                File[] files = file.listFiles();
                for (File f : files) {
                    // 递归删除
                    deleteFile(f.getPath());
                }
            }
            file.delete();
            LOGGER.info("删除文件 " + file.getPath());
        } else {
        }
    }

    /**
     * 删除文件夹内 过期文件夹、文件
     *
     * @param dirName 文件夹
     * @param day 过期时间
     */
    public static void deleteExpiredFile(String dirName, int day) {
        int count = 0;
        long time = (long) day * 24 * 60 * 60 * 1000;
        File dir = new File(dirName);
        if (!dir.exists()) {
            LOGGER.info(dirName + "文件夹不存在");
            return;
        }
        List<File> files = getAllFiles(dir);
        // 删除所有过期的子文件
        for (File file : files) {
            long tmp = System.currentTimeMillis() - file.lastModified();
            if (tmp > time) {
                //Expired
                file.delete();
                count++;
                LOGGER.info("delete " + file.getAbsolutePath());
                LOGGER.info("delete " + file.getAbsolutePath() + " 当前：" + DateUtil.getFormatTimeByLong(System.currentTimeMillis())
                        + "最后修改：" + DateUtil.getFormatTimeByLong(file.lastModified()));
            }
        }
        // 删除空子文件夹（即使没过期也删除）
        for (File f : dir.listFiles()) {
            if (f.isDirectory()) {
                clear(f);
            }
        }
        LOGGER.info("已删除" + count + "个过期文件！");
    }

    /**
     * 删除空文件夹
     *
     * @param dir
     */
    public static void clear(File dir) {
        File[] dirs = dir.listFiles();
        // 递归条件
        for (int i = 0; i < dirs.length; i++) {
            if (dirs[i].isDirectory()) {
                clear(dirs[i]);
            }
        }
        // 递归出口
        if (dir.isDirectory() && dir.listFiles().length == 0) {
            dir.delete();
        }
    }

    /**
     * 递归获得文件夹下所有文件
     *
     * @param dir
     * @return
     */
    public static List<File> getAllFiles(File dir) {
        ArrayList<File> files = new ArrayList<>();
        if (dir.listFiles().length == 0) {
            return files;
        }
        for (File file : dir.listFiles()) {
            if (file.isFile()) {
                files.add(file);
            } else if (file.isDirectory()) {
                files.addAll(getAllFiles(file));
            }
        }
        return files;
    }

    /**
     * 生成二维数组
     * @param startVal  [0][0]的值
     * @param layerNums 行数
     * @param shelfNums 列数
     * @return
     */
    public static String[][] createShelfNo(int startVal,int layerNums,int shelfNums){
        String[][] result = new String[layerNums][shelfNums];
        for (int m = 0; m < layerNums; m ++){
            for (int n = 0; n <shelfNums  ; n++){
                result[m][n] = "A00"+String.format("%03d",(startVal + m + layerNums * n));
            }
        }
        return result;
    }
}
